import akshare as ak
import pandas as pd
import random

def get_chinext_index():
    try:
        # 获取中国创业板指数分钟级别数据
        stock_zh_a_minute_df = ak.stock_zh_a_minute(symbol="sz399006", period="30", adjust="qfq")

        # 处理数据结构
        stock_zh_a_minute_df.reset_index(inplace=True)
        stock_zh_a_minute_df['timestamp'] = pd.to_datetime(stock_zh_a_minute_df['index'])
        stock_zh_a_minute_df['open'] = stock_zh_a_minute_df['open']
        stock_zh_a_minute_df['high'] = stock_zh_a_minute_df['high']
        stock_zh_a_minute_df['low'] = stock_zh_a_minute_df['low']
        stock_zh_a_minute_df['close'] = stock_zh_a_minute_df['close']
        stock_zh_a_minute_df['volume'] = stock_zh_a_minute_df['volume']

        # 选择所需的列并重命名
        data = stock_zh_a_minute_df[['timestamp', 'open', 'high', 'low', 'close', 'volume']]
        data = data.sort_values(by='timestamp')

        # 随机选择一个开始时间
        max_start_index = len(data) - 500
        start_index = random.randint(0, max_start_index)
        random_500_data = data.iloc[start_index:start_index + 500]

        # 保存为CSV文件
        random_500_data.to_csv('chinext_index.csv', index=False)
        print("创业板指数随机500根K线数据已保存到 chinext_index.csv")
    except Exception as e:
        print(f"获取数据时发生错误: {e}")

if __name__ == '__main__':
    get_chinext_index()
